//
//  NRWMarketingToolsVC.m
//  New_Runway
//
//  Created by 张记 on 2018/5/28.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "NRWMarketingToolsVC.h"
#import "NRWCarListShareCell.h"
#import "LYSideslipCell.h"
#import "NRWCarSearchView.h"
#import "NRWCarListsModel.h"
#import "CarDetailMainVC.h"
#import "NRWCarLongPressView.h"
#import "NRWCarShareBottomView.h"
#import "ChooseCarToShareView.h"
#import "NRWCanChooseCarLisetCell.h"
#import "NRWCarMorePictureToShareVC.h"
#import "NRWCarListToShareVC.h"
#import "NRWCarShareTool.h"
#import "NRWCarShareTemplateManager.h"
#import "NRWCarSharePictureModel.h"
#import <CoreImage/CoreImage.h>
@interface NRWMarketingToolsVC ()<UITableViewDelegate,
UITableViewDataSource,
UIGestureRecognizerDelegate,
LYSideslipCellDelegate,
UITextFieldDelegate,
NRWCarSearchViewDelegate>
@property(nonatomic, strong) UITableView *tableview;
@property (assign, nonatomic) NSInteger pageNo;
@property (nonatomic, strong) NSMutableArray *carArray;
@property (strong, nonatomic) NRWCarSearchView *searchView;
@property (strong, nonatomic) NSMutableDictionary *AllDic;
@property (strong, nonatomic) NSMutableDictionary *contentOffset;
@property (strong, nonatomic) NRWCarLongPressView *longView;
@property (strong, nonatomic) NRWCarShareBottomView *shareBottomView;
@property (nonatomic, assign) BOOL isSelected;
@property (nonatomic, assign) BOOL allSelected;
@property (nonatomic, strong) NSMutableArray *selectedArray;
@property (nonatomic, strong) UIButton *sharePictureButton;
@property (nonatomic, strong) UIButton *shareListButton;
@property (nonatomic, strong) UIButton *chooseShareB;

@end

@implementation NRWMarketingToolsVC
-(NSMutableArray *)carArray{
    if (!_carArray) {
        _carArray = [[NSMutableArray alloc] init];
    }
    return _carArray;
}
-(NSMutableDictionary *)AllDic{
    if (!_AllDic) {
        _AllDic = [[NSMutableDictionary alloc] init];
    }
    return _AllDic;
}
-(NSMutableDictionary *)contentOffset{
    if (!_contentOffset) {
        _contentOffset = [[NSMutableDictionary alloc] init];
    }
    return _contentOffset;
}
-(NSMutableArray *)selectedArray{
    if (!_selectedArray) {
        _selectedArray = [[NSMutableArray alloc] init];
    }
    return _selectedArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.pageNo = 1;
    [self initTableview];
    [self setupSearchBar];
    [self loadCarList];
    [self addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
    [self setChooseHeaderView];
}
-(void)setChooseHeaderView{
    ChooseCarToShareView *chooseShareView =[[[NSBundle mainBundle] loadNibNamed:@"ChooseCarToShareView" owner:self options:nil]lastObject];
    chooseShareView.frame = CGRectMake(0, self.navH, Screen_width, 44);
    self.chooseShareB = chooseShareView.chooseCarB;
    kSelfWeak;
    chooseShareView.ChooseShareBlock = ^(BOOL isSelected) {
        weakSelf.isSelected = isSelected;
        
        if (isSelected == YES) {
            [self shareButtonShowAnimate];
           
        }else{
            for (Result *rt in self.carArray) {
                if (rt.selected == YES) {
                    rt.selected = NO;
                }
            }
            [self shareButtonHiddenAnimate];
            [weakSelf.selectedArray removeAllObjects];
        }
        [weakSelf.tableview reloadData];

    };
    chooseShareView.ChooseAllCarBlock = ^(BOOL AllSelected) {
        weakSelf.allSelected = AllSelected;
        [weakSelf.tableview reloadData];
    };
    [self.view addSubview:chooseShareView];
}
-(void)shareButtonShowAnimate{
    self.chooseShareB.userInteractionEnabled = NO;
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        
        _shareListButton.hidden = NO;
        _sharePictureButton.hidden = NO;
        _shareListButton.frame = CGRectMake(Screen_width - 98, Screen_height - self.BotH - 98 - 32, 98, 98);
        _sharePictureButton.frame = CGRectMake(Screen_width - 98, Screen_height - self.BotH - 98 - 32, 98, 98);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:1 delay:0.2 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:UIViewAnimationOptionCurveEaseOut animations:^{
            _sharePictureButton.frame = CGRectMake(Screen_width - 98, Screen_height - self.BotH - 98 * 2 - 20, 98, 98);
            
        } completion:^(BOOL finished) {
            self.chooseShareB.userInteractionEnabled = YES;

        }];
    }];
   
}
-(void)shareButtonHiddenAnimate{
    self.chooseShareB.userInteractionEnabled = NO;
    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        _shareListButton.hidden = NO;
        _sharePictureButton.hidden = NO;
        _sharePictureButton.frame = CGRectMake(Screen_width - 98, Screen_height - self.BotH - 98 - 32, 98, 98);
   
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.5 delay:0.2 usingSpringWithDamping:0.8 initialSpringVelocity:0.6 options:UIViewAnimationOptionCurveEaseOut animations:^{
            _shareListButton.frame = CGRectMake(Screen_width , Screen_height - self.BotH - 98 - 32, 98, 98);
            _sharePictureButton.frame = CGRectMake(Screen_width , Screen_height - self.BotH - 98 - 32, 98, 98);
        } completion:^(BOOL finished) {
            _shareListButton.hidden = YES;
            _sharePictureButton.hidden = YES;
            self.chooseShareB.userInteractionEnabled = YES;
        }];
        
    }];
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"contentOffset"]) {
        [self.longView removeFromSuperview];
    }
}
-(void)initTableview{
    kSelfWeak;
    self.tableview = [[UITableView alloc] init];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    _tableview.estimatedRowHeight = 0;
    _tableview.estimatedSectionHeaderHeight = 0;
    _tableview.estimatedSectionFooterHeight = 0;
    if (@available(iOS 11.0, *)) {
        self.tableview.contentInsetAdjustmentBehavior = UIApplicationBackgroundFetchIntervalNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = false;
    }
    self.tableview.backgroundColor = MAIN_COLOR();
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.tableview registerNib:[UINib nibWithNibName:@"NRWCanChooseCarLisetCell" bundle:nil] forCellReuseIdentifier:@"NRWCanChooseCarLisetCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"NRWCarListShareCell" bundle:nil] forCellReuseIdentifier:@"NRWCarListShareCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"NRWCarListRejectCell" bundle:nil] forCellReuseIdentifier:@"NRWCarListRejectCell"];
    self.tableview.mj_header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downPullRefresh)];
    self.tableview.mj_footer=[MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upPullLoadMore)];
    [self.view addSubview:self.tableview];
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).mas_equalTo(self.navH + 44);
        make.bottom.equalTo(weakSelf.view);
        make.left.right.equalTo(weakSelf.view);
    }];
    
    _sharePictureButton = [[UIButton alloc] init];
    _sharePictureButton.hidden = YES;
    [_sharePictureButton setImage:[UIImage imageNamed:@"share_more_picture"]  forState:UIControlStateNormal];
    _sharePictureButton.frame = CGRectMake(Screen_width , Screen_height - self.BotH - 98 - 32, 98, 98);
    [_sharePictureButton addTarget:self action:@selector(sharePictureDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_sharePictureButton];
    
    _shareListButton = [[UIButton alloc] init];
    _shareListButton.hidden = YES;
    [_shareListButton setImage:[UIImage imageNamed:@"share_To_list"]  forState:UIControlStateNormal];
    _shareListButton.frame = CGRectMake(Screen_width, Screen_height - self.BotH - 98 - 32, 98, 98);
    [_shareListButton addTarget:self action:@selector(shareListDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_shareListButton];
    
   
}
-(void)shareListDidClick:(UIButton *)sender{
   
        if (self.selectedArray.count > 100) {
            [ShowMessage showHintMessage:@"最多分享100辆车" duration:2.0 withRemindId:remindWarning];
     
        }else if (self.selectedArray.count < 2){
            [ShowMessage showHintMessage:@"至少选择2辆车分享" duration:2.0 withRemindId:remindWarning];
         
        }else{
            
            NRWCarListToShareVC *listShareVC = [[NRWCarListToShareVC alloc] init];
            listShareVC.dataArray = self.selectedArray;
            [self.navigationController pushViewController:listShareVC animated:YES];
        }
}
-(void)sharePictureDidClick:(UIButton *)sender{
    if (self.selectedArray.count > 8) {
        [ShowMessage showHintMessage:@"最多分享8辆车" duration:2.0 withRemindId:remindWarning];
        
    }else if (self.selectedArray.count < 1){
        [ShowMessage showHintMessage:@"至少选择1辆车分享" duration:2.0 withRemindId:remindWarning];
    }else{
        [self loadMarketCode];
    }
}
-(void)loadMarketCode{
    
    NSString *shopID;
    if ([NRWCarUser sharedUser].shopId) {
        shopID = [NRWCarUser sharedUser].shopId;
    }else{
        shopID = @"";
    }
    
   NSString *urlstr = [NSString stringWithFormat:@"%@/mshop/src/home.html?shopId=%@&marketId=%@&imgUrl=%@&os=ios",Api,shopID,[NRWCarUser sharedUser].marketId,ImageApi];
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [filter setDefaults];
    NSData *data = [urlstr dataUsingEncoding:NSUTF8StringEncoding];
    [filter setValue:data forKeyPath:@"inputMessage"];
    CIImage *image = [filter outputImage];
    NRWCarSharePictureModel *imageModel = [[NRWCarSharePictureModel alloc] init];
    imageModel.isMark = NO;
    imageModel.isSelected = YES;
    imageModel.isTemplate = NO;
    imageModel.imageType = 2;
    imageModel.picture =  [self createNonInterpolatedUIImageFormCIImage:image withSize:Screen_width];
    NRWCarMorePictureToShareVC *pictureShareVC = [[NRWCarMorePictureToShareVC alloc] init];
    pictureShareVC.dataArray = self.selectedArray;
    pictureShareVC.imageModel = imageModel;
    [self.navigationController pushViewController:pictureShareVC animated:YES];
    
}
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat)size {
    
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 110;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.carArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    Result *rt = self.carArray[indexPath.row];
    if (self.isSelected == YES) {
        NRWCanChooseCarLisetCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NRWCanChooseCarLisetCell"];
        cell.carModel = rt;
        return cell;
    }
    NRWCarListShareCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NRWCarListShareCell"];
    cell.index = indexPath;
    cell.carModel = rt;
    cell.delegate = self;
    UILongPressGestureRecognizer * longPressGesture =[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(cellLongPress:)];
    longPressGesture.minimumPressDuration=1.0f;//设置长按 时间
    [cell addGestureRecognizer:longPressGesture];
    return cell;
}
-(void)cellLongPress:(UILongPressGestureRecognizer *)longRecognizer{
    
    if (longRecognizer.state==UIGestureRecognizerStateBegan) {
        [self becomeFirstResponder];
        [self.longView removeFromSuperview];
        CGPoint location = [longRecognizer locationInView:self.tableview];
        NSIndexPath *indexPath = [self.tableview indexPathForRowAtPoint:location];
        NRWCarListShareCell *cell = [self.tableview cellForRowAtIndexPath:indexPath];
        Result *rt = self.carArray[indexPath.row];
        self.longView = [[NRWCarLongPressView alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)];
        self.longView.model = rt;
        [cell.contentView addSubview:_longView];
        
    }
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    Result *rt = self.carArray[indexPath.row];

    if (self.isSelected == YES) {
        if (rt.selected == YES) {
            rt.selected = NO;
            [self.selectedArray removeObject:rt];
        }else{
            rt.selected = YES;
            [self.selectedArray addObject:rt];
        }
        [self.tableview reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:indexPath.row inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        return;
    }
    
    CarDetailMainVC *carDVC = [[CarDetailMainVC alloc] init];
    carDVC.selIndex = indexPath;
    carDVC.isShowR = YES;
    carDVC.isShowShare = YES;
//    carDVC.showImageId = 1;
    carDVC.carID = rt.carId;
    carDVC.modelID = rt.modelId;
    carDVC.isReject = rt.carStockState;
    [self.navigationController pushViewController:carDVC animated:YES];
    [self willChangeValueForKey:@"contentOffset"];
    [self.contentOffset  setValue:@(1) forKey:@"contentOffset"];
    [self didChangeValueForKey:@"contentOffset"];
    
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self willChangeValueForKey:@"contentOffset"];
    [self.contentOffset  setValue:@(scrollView.contentOffset.y) forKey:@"contentOffset"];
    [self didChangeValueForKey:@"contentOffset"];
}

-(void)downPullRefresh{
    [self.selectedArray removeAllObjects];
    self.pageNo = 1;
    [self loadCarList];
}
-(void)upPullLoadMore{
    self.pageNo += 1;
    [self loadCarList];
    
}

- (void)setupSearchBar {
    
    _searchView = [[NRWCarSearchView alloc] initWithPlaceHold:@"请输入VIN码后六位进行查询" leftImageName:@"icon_search_vin" rightImageName:@"icon_delete_vin"];
    _searchView.delegate_custom = self;
    _searchView.delegate = self;
    self.navigationBarView.addSubview(_searchView);
    
    _searchView.layer.cornerRadius = 13;
    _searchView.layer.masksToBounds = YES;
    [_searchView addTarget:self action:@selector(searchViewTextChange:) forControlEvents:UIControlEventEditingChanged];
    
    [_searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.navigationBarView.mas_left).offset(62);
        make.right.equalTo(self.navigationBarView.mas_right).offset(-62);
        make.height.equalTo(@27);
        make.bottom.equalTo(self.navigationBarView.mas_bottom).offset(-8);
    }];
}
#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if (textField.text.length != 6) {
        [ShowMessage showHintMessage:@"请输入VIN码后六位" duration:2 withRemindId:remindWarning];
        return NO;
    }
    
    [self.AllDic setObject:textField.text forKey:@"carVin6"];
    
    [self downPullRefresh];
    
    return YES;
}

- (void)searchView:(NRWCarSearchView *)searchView rightBtnDidClick:(UIButton *)sender {
    
    [self.AllDic removeObjectForKey:@"carVin6"];
    self.searchView.text = nil;
    [searchView resignFirstResponder];
    [self downPullRefresh];
}

- (void)searchViewTextChange:(UITextField *)sender {
    
    if (_searchView.text.length > 6) {
        
        _searchView.text = [_searchView.text substringToIndex:6];
    }
}
-(void)loadCarList{
    
    NSDictionary *params = @{@"marketId":[NRWCarUser sharedUser].marketId,
                             @"pageSize":@(15),
                             @"pageIndex":@(self.pageNo),
                             @"shopId":[NRWCarUser sharedUser].shopId ? [NRWCarUser sharedUser].shopId : @"",
                             @"carStockState":@(20),
                             @"orderColunm":@"CAR_STOCK_TIME",
                             @"orderMode":@"DESC"
                             };
    [self.AllDic addEntriesFromDictionary:params];
    NSString *url = [NSString stringWithFormat:@"%@%@",Api,carListsApi];
    [SVProgressHUD show];
    [YQNetworking postWithUrl:url refreshRequest:YES cache:NO params:self.AllDic progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        if (self.pageNo == 1) {
            [self.carArray removeAllObjects];
        }
        NSArray *noticeArr = response[@"result"];
        for (NSDictionary *dic in noticeArr) {
            Result *rt = [Result mj_objectWithKeyValues:dic];
            [self.carArray addObject:rt];
        }
        if (self.carArray.count == 0) {
            [self.tableview addDefaultViewWithText:@"暂无数据" defaultImageType:DefaultImageTypeNoData];
        }else{
            [self.tableview removeDefaultView];
        }
        [self.tableview reloadData];
        [self endRefresh];
        [SVProgressHUD dismiss];
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"加载数据失败" duration:2.0 withRemindId:remindFail];
        [self endRefresh];
        [SVProgressHUD dismiss];
        
    }];
}
-(void)endRefresh{
    [self.tableview.mj_header endRefreshing];
    [self.tableview.mj_footer endRefreshing];
    
}
- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo{
    NSIndexPath *index = userInfo[@"index"];
    Result *rt = self.carArray[index.row];
    [self.searchView resignFirstResponder];
    self.shareBottomView = [[[NSBundle mainBundle] loadNibNamed:@"NRWCarShareBottomView" owner:self options:nil]lastObject];
    self.shareBottomView.shareBlock = ^(NSString *content, NSInteger type) {
        if (type == 2 ) {
            [NRWCarShareTool shareCarDetailWithCarDetailModel:rt customerTitle:content shareType:ShareTypeWeiXin];
        }else if (type == 1){
            [NRWCarShareTool shareCarDetailWithCarDetailModel:rt customerTitle:content shareType:ShareTypeWXCircle];
        }
    };
    self.shareBottomView.imageUrl = rt.carImageUrl;
    self.shareBottomView.contentF.text = rt.carTitle;
    self.shareBottomView.frame = self.view.frame;
    [self.view addSubview:self.shareBottomView];
    [self.shareBottomView show];
    
    
    

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
-(void)dealloc{
    [self removeObserver:self forKeyPath:@"contentOffset"];
}


@end
